﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-21 15:32
    /// 描 述：关联类型表
    /// </summary>
    public class ec_WireTerminalService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_WireTerminalEntity> _wireTerminalRepository => new Repository<ec_WireTerminalEntity>();
        #endregion
        #region 获取数据

        public ec_WireTerminalEntity GetEntity(string ProjectId, string keyValue)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    return null;
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    var strSql = new StringBuilder();
                    strSql.Append($@"SELECT * FROM ec_wire_terminal_{ProjectEntity.ProjectIndex} WHERE ID = '{keyValue}' ");
                    //List<ec_WireTerminalEntity> list = this.BaseRepository().FindList<ec_WireTerminalEntity>(strSql.ToString()).ToList();
                    //return list.FirstOrDefault();
                    return SqlSugarHelper.Db.Ado.SqlQuerySingle<ec_WireTerminalEntity>(strSql.ToString());
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_WireTerminalEntity> GetList(string queryJson, bool onlySelf = false)
        {
            try
            {
                var ProjectEntity = new ec_projectEntity();
                //参考写法
                var queryParam = queryJson.ToJObject();
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT t8.TagNumber PanelName,t3.StripName,t4.Term_No,t4.Term_Seq,t9.TagNumber CableName,t6.CableSetName,t6.CableSetSeq,t7.Wire_Tag,t7.Polarity,t7.SetLevel,t6.CablesetID,t.* ");
                if (queryParam["ProjectId"].IsEmpty())
                {
                    return null;
                }
                else
                {

                    //ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(queryParam["ProjectId"].ToString());
                    ProjectEntity = _projectRepository.GetById(queryParam["ProjectId"].ToString());


                    if (onlySelf)
                    { 
                        return _wireTerminalRepository.AsQueryable().AS($"ec_wire_terminal_{ ProjectEntity.ProjectIndex}").ToList();
                    }

                    strSql.Append($" FROM ec_wire_terminal_{ProjectEntity.ProjectIndex} t " +
                        $"join ec_panel_strip_term_{ProjectEntity.ProjectIndex} t4 on t.termid=t4.termid " +
                        $"join ec_panel_strip_{ProjectEntity.ProjectIndex} t3 on t4.stripid=t3.stripid " +
                        $"join ec_panel_{ProjectEntity.ProjectIndex} t2 on t3.panelid=t2.panelid " +
                        $"join ec_cable_set_wire_{ProjectEntity.ProjectIndex} t7 on t.wireid=t7.wireid " +
                        $"join ec_cable_set_{ProjectEntity.ProjectIndex} t6 on t7.cablesetid=t6.cablesetid " +
                        $"join ec_cable_{ProjectEntity.ProjectIndex} t5 on t6.cableid=t5.cableid " +

                        $"join ec_enginedata_{ProjectEntity.ProjectIndex} t8 on t8.EngineDataID=t2.EngineerDataID " +
                        $"join ec_enginedata_{ProjectEntity.ProjectIndex} t9 on t9.EngineDataID=t5.EngineerDataID ");
                }
                strSql.Append(" WHERE 1=1 ");
                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["PanelID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("PanelID", queryParam["PanelID"].ToString(), DbType.String));
                    strSql.Append(" AND t2.PanelID = @PanelID ");
                }
                if (!queryParam["StripID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("StripID", queryParam["StripID"].ToString(), DbType.String));
                    strSql.Append(" AND t3.StripID = @StripID ");
                }
                if (!queryParam["termid"].IsEmpty())
                {
                    dp.Add(new SugarParameter("termid", queryParam["termid"].ToString(), DbType.String));
                    strSql.Append(" AND t.termid = @termid ");
                }
                if (!queryParam["CableID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("CableID", queryParam["CableID"].ToString(), DbType.String));
                    strSql.Append(" AND t5.CableID = @CableID ");
                }
                if (!queryParam["CableSetID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("CableSetID", queryParam["CableSetID"].ToString(), DbType.String));
                    strSql.Append(" AND t6.CableSetID = @CableSetID ");
                }
                if (!queryParam["wireid"].IsEmpty())
                {
                    dp.Add(new SugarParameter("wireid", queryParam["wireid"].ToString(), DbType.String));
                    strSql.Append(" AND t.wireid = @wireid ");
                }
                //return this.BaseRepository().FindList<ec_WireTerminalEntity>(strSql.ToString(), dp);
                return SqlSugarHelper.Db.SqlQueryable<ec_WireTerminalEntity>(strSql.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        #endregion

        #region 提交数据
        /// <summary>
        /// 删除实体数据
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="connID">按id删</param>
        /// <param name="entity">有的话，可以不按照id来，而是按照其他的条件删</param>
        public void DeleteEntity(string ProjectId, string connID, ec_WireTerminalEntity entity)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                //关联类型删除时，删除工程数据关联表记录。
                if (string.IsNullOrWhiteSpace(ProjectId))
                {

                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    if (entity != null)
                    {
                        //删除已有的
                        _wireTerminalRepository.AsDeleteable().Where(x =>
                        x.WireID == entity.WireID
                        && x.TermID == entity.TermID).AS($"ec_wire_terminal_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }


                    SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_wire_terminal_{ProjectEntity.ProjectIndex} WHERE ID = '{connID}';");
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string ProjectId, string keyValue, ec_WireTerminalEntity entity)
        {
            try
            {
                var ProjectEntity = new ec_projectEntity();
                if (!string.IsNullOrWhiteSpace(ProjectId))
                {
                    ProjectEntity = _projectRepository.GetById(ProjectId);
                }
                else
                {
                    return;
                }

                if (!string.IsNullOrEmpty(keyValue))
                {

                    //entity.Modify(keyValue); //否则save时，会错误地刷掉修改者信息
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _wireTerminalRepository.Update(entity);
                    }
                    else
                    {
                        //this.BaseRepository().UpdateByNoMap(entity, $"ec_wire_terminal_{ProjectEntity.ProjectIndex}", "ID");
                        _wireTerminalRepository.AsUpdateable(entity).AS($"ec_wire_terminal_{ProjectEntity.ProjectIndex}").
                            IgnoreColumns(x => x.UpdateUserID).
                            IgnoreColumns(x => x.CreateUserID).
                            ExecuteCommand();
                    }


                }
                else
                {
                    entity.Create();
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _wireTerminalRepository.Insert(entity);
                    }
                    else
                    {
                        //删除已有的
                        _wireTerminalRepository.AsDeleteable().Where(x =>
                        x.WireID == entity.WireID
                        && x.TermID == entity.TermID).AS($"ec_wire_terminal_{ProjectEntity.ProjectIndex}").ExecuteCommand();

                        _wireTerminalRepository.AsInsertable(entity).AS($"ec_wire_terminal_{ProjectEntity.ProjectIndex}").
                            IgnoreColumns(x => x.UpdateUserID).
                            ExecuteCommand();

                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

    }
}
